package com.yxt.admin.controller;

import com.yxt.admin.bean.TokenService;
import com.yxt.admin.config.ResourceServerConfig;
import com.yxt.admin.dto.UserDto;
import com.yxt.admin.entity.SysMenu;
import com.yxt.admin.service.ISysMenuService;
import com.yxt.admin.utils.SecurityUtils;
import com.yxt.common.annotation.Log;
import com.yxt.common.constant.Constant;
import com.yxt.common.enums.BusinessType;
import com.yxt.common.utils.ServletUtils;
import com.yxt.common.utils.StringUtils;
import com.yxt.common.utils.ajax.R;
import com.yxt.common.utils.redis.RedisCache;
import com.yxt.common.utils.sign.JwtUtil;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 * 
 */
@RestController
@RequestMapping("/admin/menu")
public class SysMenuController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    TokenService tokenService;

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public R list(SysMenu menu)
    {
        List<SysMenu> menus = menuService.selectMenuList(menu, tokenService.getLoginUser().getUser().getUserId());
        return R.ok().put("data",menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public R getInfo(@PathVariable Long menuId)
    {
        return R.ok().put("data",menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public R treeselect(SysMenu menu)
    {
        List<SysMenu> menus = menuService.selectMenuList(menu, tokenService.getLoginUser().getUser().getUserId());

        return R.ok().put("data",menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public R roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysMenu> menus = menuService.selectMenuList(tokenService.getLoginUser().getUser().getUserId());
        return R.ok().put("checkedKeys",menuService.selectMenuListByRoleId(roleId))
                .put("menus",menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 新增菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysMenu menu)
    {
        if (Constant.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return R.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (Constant.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constant.HTTP, Constant.HTTPS))
        {
            return R.error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }


        menu.setCreateBy(tokenService.getLoginUser().getUser().getUserName());

        return menuService.insertMenu(menu) > 0 ? R.ok() : R.error();
    }

    /**
     * 修改菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysMenu menu)
    {
        if (Constant.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return R.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (Constant.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constant.HTTP, Constant.HTTPS))
        {
            return R.error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return R.error("新增菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());

        return menuService.updateMenu(menu) > 0 ? R.ok() : R.error();
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public R remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return R.error("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return R.error("菜单已分配,不允许删除");
        }
        return menuService.deleteMenuById(menuId) > 0 ? R.ok() : R.error();
    }
}